package com.xdf.ecommerce.service.async;

import com.xdf.ecommerce.constant.AsyncTaskStatusEnum;
import com.xdf.ecommerce.goods.GoodsInfo;
import com.xdf.ecommerce.vo.AsyncTaskInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 异步任务管理器，对异步任务进行包装，记录并填充异步任务执行信息
 * @author chanchaw
 * @create 2025-10-28 14:05
 */
@RequiredArgsConstructor
@Slf4j
@Component
public class AsyncTaskManager {
    private final IAsyncService asyncService;
    // 保存异步任务执行的信息
    private final Map<String, AsyncTaskInfo> taskContainer = new HashMap<>(16);

    /**
     * 初始化得到一个异步任务信息对象
     * @return
     */
    public AsyncTaskInfo initTask(){
        AsyncTaskInfo taskInfo = new AsyncTaskInfo();
        taskInfo.setTaskId(UUID.randomUUID().toString());
        taskInfo.setStatus(AsyncTaskStatusEnum.STATED);
        taskInfo.setStartTime(LocalDateTime.now());
        taskContainer.put(taskInfo.getTaskId(), taskInfo);
        return taskInfo;
    }

    public AsyncTaskInfo submit(List<GoodsInfo> goodsInfos){
        AsyncTaskInfo asyncTaskInfo = initTask();
        asyncService.asyncGoodsInfo(goodsInfos,asyncTaskInfo.getTaskId());
        return asyncTaskInfo;
    }

    public void setTaskInfo(AsyncTaskInfo taskInfo){
        taskContainer.put(taskInfo.getTaskId(), taskInfo);
    }
    public AsyncTaskInfo getAsyncTaskInfo(String taskId){
        return taskContainer.get(taskId);
    }
}
